package com.jmu.edu.IMApplication.fragment;

import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.google.android.material.button.MaterialButton;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jmu.edu.IMApplication.MyApplication;
import com.jmu.edu.IMApplication.R;
import com.jmu.edu.IMApplication.adapter.MatchItemAdapter;
import com.jmu.edu.IMApplication.net.bean.Match;
import com.jmu.edu.IMApplication.utils.HttpUtil;
import com.jmu.edu.IMApplication.utils.ViewUtils;
import com.wang.avi.AVLoadingIndicatorView;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class MatchResultFragment extends Fragment {

    private static final String TAG = "matchResult";
    private RecyclerView recyclerView;
    private MaterialButton changeButton, backButton;
    private MatchItemAdapter adapter;
    private List<Match> matchList;
    private AVLoadingIndicatorView animation;

    public MatchResultFragment() {
        // Required empty public constructor
    }

    public void setMatchList(List<Match> matchList) {
        this.matchList = matchList;
        for (Match match : matchList) {
            Log.d("匹配结果", match.getOtherUserName() + "||" + match.getMatching() + "||" + match.getMatchHobbiesList().toString());
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_match_result, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
    }

    private void initView() {
        animation = getView().findViewById(R.id.fragment_match_result_animation);
        animation.hide();
        changeButton = getView().findViewById(R.id.fragment_match_result_change_button);
        backButton = getView().findViewById(R.id.fragment_match_result_back);
        recyclerView = getView().findViewById(R.id.fragment_match_result_recyclerView);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
        recyclerView.setLayoutManager(linearLayoutManager);
        if (adapter == null) {
            adapter = new MatchItemAdapter();
        }
        initListener();
        loadData();

    }

    private void initListener() {
        backButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ViewUtils.hideFragment(MatchResultFragment.this, R.anim.from_left, R.anim.out_right);
            }
        });
        changeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                animation.show();
                getMatchListFromServer();
            }
        });
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        if (hidden) {

        } else {
            loadData();
        }
    }

    private void getMatchListFromServer() {
        Map<String, String> map = new HashMap<>();
        map.put("username", MyApplication.getUser().getUserName());
        RequestBody requestBody = RequestBody.create(HttpUtil.JSON, new Gson().toJson(map));
        Request request = new Request.Builder().url(HttpUtil.URL_GET_MATCH_LIST).post(requestBody).build();
        MyApplication.getClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e(TAG, "onFailure: ", e);
                //结束加载动画
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        animation.hide();
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //结束加载动画
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        animation.hide();
                    }
                });
                String json = response.body().string();
                Log.d(TAG, "onResponse: " + json);
                TypeToken<List<Match>> typeToken = new TypeToken<List<Match>>() {
                };
                matchList = new Gson().fromJson(json, typeToken.getType());
                if (matchList == null) {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getContext(), "已经没有新的匹配用户啦！请稍后再试！", Toast.LENGTH_SHORT).show();
                        }
                    });
                } else {
                    loadData();
                }
            }
        });
    }

    public void loadData() {
        //将数据放入adapter，同时使recyclerView使用适配器
        adapter.setContext(getContext());
        adapter.setMatchList(matchList);
        if (recyclerView.getAdapter() == null) {
            recyclerView.setAdapter(adapter);
        }else{
            adapter.notifyDataSetChanged();
        }
        ViewUtils.addBackListenerForHide(getView(), backButton);
    }
}